package lol.niconico.libtest.http

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.Response
import okhttp3.WebSocket

import okhttp3.WebSocketListener

import okhttp3.mockwebserver.MockResponse

import okhttp3.mockwebserver.MockWebServer


/**
 * Created by ZhangQianqian on 2020/7/9  16:33.
 * email 415692689@qq.com
 */
object Server {

    lateinit var webSocket: WebSocket
    private val mockWebServer: MockWebServer = MockWebServer()

    fun startServer() {
        val response = MockResponse()
            .withWebSocketUpgrade(object : WebSocketListener() {
                private val TAG = "Server WsListener"

                override fun onOpen(webSocket: WebSocket, response: Response) {
                    super.onOpen(webSocket, response)
                    this@Server.webSocket = webSocket
                    //有客户端连接时回调
                    Log.e(TAG, "服务器收到客户端连接成功回调：")
                    webSocket.send("我是服务器，你好呀")
                }

                override fun onMessage(webSocket: WebSocket, text: String) {
                    super.onMessage(webSocket, text)
                    Log.e(TAG, "服务器收到消息：$text")
                }

                override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
                    super.onClosed(webSocket, code, reason)
                    Log.e(TAG, "onClosed：")
                }
            })
        mockWebServer.enqueue(response)

        GlobalScope.launch(Dispatchers.IO) {
            val mWbSocketUrl = "ws://" + mockWebServer.hostName + ":" + mockWebServer.port + "/"
            withContext(Dispatchers.Main) {
                Client.startClient(mWbSocketUrl)
            }
        }
    }
}

